//
//  UITextView+Extension.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/16.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit


extension UITextView {
    
    //    MARK: - 获取发布微博的表情
     func getPublishText() ->String{
//                print(self.text)
//                print(self.attributedText)
        var publistText = ""
        
        /*
        NSAttachment = "<NSTextAttachment: 0x7fde0a80f1a0>";
        NSFont = "<UICTFont: 0x7fde08716480> font-family: \".SFUIText-Regular\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
        */
        //对
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0,self.attributedText.length), options: []) { (data:[String: AnyObject], range:NSRange, _) -> Void in
//                      print(data)
//                        print("+++++++++++++++++++")
//                        print(range)
            
            if let attachment = data["NSAttachment"] as? WBTextAttachment {
                
                if let chs = attachment.emoticon?.chs {
                    publistText = publistText + chs
                    //的到表情的chs
                }
                
            }else {
                let text = (self.text as NSString).substringWithRange(range)
                
                publistText = publistText + text
                
            }
        }
        //print(publistText)
        return publistText
    }


    //对显示表情的抽取
    func insertEmoticon(emoticon: WBEmoticon) {
        //printLog(emoticon.png)
       
        if let _ = emoticon.png{ //判断是有png
           
            //1.保存原来的
            let orginal = NSMutableAttributedString(attributedString: self.attributedText)

            let attribue = WBTextAttachment.getEmoiconAttributeString(emoticon, fontHeight: 16)
            
            //光标的位置
            let range = self.selectedRange
            //2.新的表情的添加之后拼接
            orginal.replaceCharactersInRange(range, withAttributedString: attribue)
            
            //改变显示 的位置还需要改变bounds
            orginal.addAttributes([NSFontAttributeName:self.font!], range:NSMakeRange(0,orginal.length))
            //3. 赋值
            self.attributedText = orginal
           //赋值之后去改变光标的位置
           self.selectedRange = NSMakeRange(range.location + 1, 0)
    
            //调用代理让占位内容消失 手动调用需要非可选
            self.delegate?.textViewDidChange!(self)
            
        }
        //判断emoji的显示逻辑
        if let emjio = emoticon.emoji{
            self.replaceRange(self.selectedTextRange!, withText:emjio)
        }
    }
    
    
}
